package cn.com.swu.mianyangapp.ui.message;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.alibaba.fastjson.JSON;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import cn.com.swu.mianyangapp.R;
import cn.com.swu.mianyangapp.bean.Text;

public class DraftFragment extends Fragment{


    private String texturl="http://192.168.43.211:8081/";
    public ListView draftlistView;

    public DraftAdapter draftAdapter;
    public ImageButton searchBtn;

    public FloatingActionButton addBtn;
    public EditText searchRecv;
    public EditText searchTitle;
    public List<Text> draftlist=new ArrayList<Text>();
    @SuppressLint("MissingInflatedId")
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState){
        View view=inflater.inflate(R.layout.fragment_drafttext,container,false);
        draftlistView=view.findViewById(R.id.DraftList);
        searchBtn=view.findViewById(R.id.search_btn);
        addBtn=view.findViewById(R.id.add_btn);
        searchRecv=view.findViewById(R.id.search_recv);
        searchTitle=view.findViewById(R.id.serach_title);

        String url=texturl+"queryListDraft";
        HttpUtil.sendOkHttpRequest(url, new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                System.out.println(e);
            }

            @Override
            public void onResponse(Response response) throws IOException {

                String responseData=response.body().string();
                changeWithJSONObject(responseData);
            }
        });

        //给搜索按钮设置监听事件
        searchBtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                String recvTele=searchRecv.getText().toString();
                String textTitle=searchTitle.getText().toString();
                String url=texturl+"queryListDraft"+"?recvTele="+recvTele+"&textTitle="+textTitle;
                HttpUtil.sendOkHttpRequest(url, new Callback() {
                    @Override
                    public void onFailure(Request request, IOException e) {
                        System.out.println(e);
                    }
                    @Override
                    public void onResponse(Response response) throws IOException {
                        String responseData=response.body().string();
                        changeWithJSONObject(responseData);
                    }
                });
        }
        });

        //点击列表中的某一项进入编辑页面
        draftlistView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {


                        ListView listView = (ListView) parent;
                        Text text=(Text)listView.getItemAtPosition(position);
                        String textTitle = text.getTextTitle();
                        String textContent=text.getTextContent();
                        String recvTele=text.getRecvTele();
                        Integer textID=text.getTextID();

                        // Toast.makeText(draftlist.get(position), content[position], Toast.LENGTH_LONG).show();
                        // 第二步：通过Intent跳转至新的页面
                        Intent intent = new Intent(getActivity(), EditTextActivity.class);
                        Bundle bundle=new Bundle();
                        bundle.putString("mtextTitle", textTitle);
                        bundle.putString("mtextContent",textContent);
                        bundle.putString("mrecvTele",recvTele);
                        bundle.putString("mtextID",textID.toString());
                        intent.putExtras(bundle);
                        startActivity(intent);

                }

        });

        //长按列表中的某一项进行删除
        draftlistView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {

                Text text=draftlist.get(i);
                System.out.println(text);
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

                builder.setTitle("操作提示");
                String msg="是否确认删除消息:"+text.getTextTitle().toString();
                builder.setMessage("是否确认删除消息");

                AlertDialog.Builder builder1 = builder.setPositiveButton("确定",new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        draftlist.remove(i);
                        String url=texturl+"deleteText"+"?textID="+text.getTextID();
                        HttpUtil.sendOkHttpRequest(url, new Callback() {
                            @Override
                            public void onFailure(Request request, IOException e) {
                                System.out.println(e);
                            }
                            @Override
                            public void onResponse(Response response) throws IOException {
                                String responseData=response.body().string();
                            }
                        });
                        draftAdapter = new DraftAdapter(draftlist, draftlistView);
                        draftlistView.setAdapter(draftAdapter);
                        Toast.makeText(getActivity(),"成功删除该消息",Toast.LENGTH_SHORT).show();
                    }

                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(getActivity(),"取消删除",Toast.LENGTH_SHORT).show();
                    }
                });
                AlertDialog alertDialog =builder.create();//这个方法可以返回一个alertDialog对象
                alertDialog.show();
                return true;
            }
        });

        //点击添加按钮，添加一条草稿记录
        addBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent = new Intent(getActivity(), EditTextActivity.class);
                startActivity(intent);
            }
        });


        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        String url=texturl+"queryListDraft";
        HttpUtil.sendOkHttpRequest(url, new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                System.out.println(e);
            }

            @Override
            public void onResponse(Response response) throws IOException {

                String responseData=response.body().string();
                changeWithJSONObject(responseData);
            }
        });

    }

    private void changeWithJSONObject(String jsonData) {
        //循环遍历取出json数组数据并存储到draftlist中
        draftlist=JSON.parseArray(jsonData, Text.class);
        Message msg=new Message();
        msg.what=1;
        handler.sendMessage(msg);
    }
    public Handler handler=new Handler(){
        @SuppressLint("HandlerLeak")
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1:
                    draftAdapter = new DraftAdapter(draftlist, draftlistView);
                    draftlistView.setAdapter(draftAdapter);
                    break;

            }
        }

    };
    public void showOnUIThread2(final Context context, final CharSequence text, final  int duration) {
        Looper.prepare();
        Toast toast = Toast.makeText(context, text, duration);
        toast.setGravity(Gravity.CENTER,0,0);
        toast.show();
        Looper.loop();
    }


}
